package com.hkts.management.upload.upload.controller;


import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hkts.management.common.utils.IDUtils;
import com.hkts.management.common.utils.Result;
import com.hkts.management.common.utils.ResultUtil;
import com.hkts.management.common.utils.SnowFlakeUtil;
import com.hkts.management.upload.utils.CustomPageUtils;
import com.hkts.management.upload.utils.QiniuUtil;
import com.qiniu.common.QiniuException;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hkts.management.upload.upload.service.IHktsFileRecordService;
import com.hkts.management.upload.upload.entity.HktsFileRecord;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author yck
 * @since 2021-07-12
 */
@RestController
@RequestMapping("/upload/hktsFileRecord")
public class HktsFileRecordController {
    private final Logger logger = LoggerFactory.getLogger(HktsFileRecordController.class);

    @Autowired
    public IHktsFileRecordService iHktsFileRecordService;

    @Autowired
    private QiniuUtil qiniuUtil;

    /**
     * 分页查询数据
     *
     * @param page           分页信息
     * @param hktsFileRecord 查询条件
     * @return
     */
    @ResponseBody
    @GetMapping("/getHktsFileRecordPageList")
    public Result<Object> getHontUserList(Page<HktsFileRecord> page, HktsFileRecord hktsFileRecord) {
        return ResultUtil.data(CustomPageUtils.getCustomPage(iHktsFileRecordService.selectPage(page, hktsFileRecord)));
    }

    /**
     * 保存和修改公用的
     *
     * @param hktsFileRecord 传递的实体
     * @return saveOrUpdate
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/hktsFileRecordSave")
    public Result<Object> hktsFileRecordSave(HktsFileRecord hktsFileRecord) {
        iHktsFileRecordService.saveOrUpdate(hktsFileRecord);
        return ResultUtil.success("保存成功");
    }

    /**
     * 根据id获取对象
     *
     * @param id 实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.GET, value = "/hktsFileRecordGetById")
    public Result<Object> hktsFileRecordGetById(String id) {
        HktsFileRecord byId = iHktsFileRecordService.getById(id);
        return ResultUtil.data(byId);
    }

    /**
     * 根据id删除对象
     *
     * @param id 实体ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/hktsFileRecordDelete")
    public Result<Object> hontUserDelete(String id) {
        iHktsFileRecordService.removeById(id);
        return ResultUtil.success("删除成功");
    }

    /**
     * 批量删除对象
     *
     * @param item 实体集合ID
     * @return 0 失败  1 成功
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/hktsFileRecordBatchDelete")
    public Result<Object> deleteBatchIds(String item) {
        List<String> ids = (List<String>) JSON.parse(item);
        iHktsFileRecordService.removeByIds(ids);
        return ResultUtil.success("删除成功");
    }

    @ResponseBody
    @PostMapping("/uploadImage")
    @ApiOperation(value = "文件上传")
    public Result<Object> uploadPicture(@ApiParam(name = "file", value = "照片", required = true) MultipartFile file) {
        String oldName = file.getOriginalFilename();
        //1.2使用IDUtils工具类生成新的文件名，新文件名 = newName + 文件后缀

        String newName = IDUtils.genImageName();
        assert oldName != null;
        newName = newName + oldName.substring(oldName.lastIndexOf("."));
        //1.3生成文件在服务器端存储的子目录
        String filePath = new DateTime().toString("/yyyyMMdd/");

        //2、把图片上传到图片服务器
        //2.1获取上传的io流
        InputStream input = null;
        try {
            input = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String key = String.valueOf(SnowFlakeUtil.getFlowIdInstance().nextId());
        String iamgePath = qiniuUtil.qiniuInputStreamUpload(input, key);
        /*
         * 保存图片信息
         * */
        HktsFileRecord record = new HktsFileRecord();
        LocalDateTime now = LocalDateTime.now();
        record.setId(IDUtils.genImageName());
        record.setCreateTime(now);
        record.setFileUrl(iamgePath);
        record.setFileKey(key);
        iHktsFileRecordService.save(record);

        return ResultUtil.data(iamgePath);
    }

    /*
     * 根据url删除db及远程存储文件数据
     * */
    /*
     * 删除图片
     * */
    @ResponseBody
    @PostMapping("/deleteImage")
    @ApiOperation(value = "文件删除")
    public Result<String> deletePicture(@ApiParam(name = "imageUrl", value = "图片地址", required = true) String imageUrl) throws QiniuException {
        HktsFileRecord record = new HktsFileRecord();
        record.setFileUrl(imageUrl);
        List<HktsFileRecord> hktsFileRecords = iHktsFileRecordService.selectList(record);
        if (hktsFileRecords.size() > 0) {
            qiniuUtil.deleteImage(hktsFileRecords.get(0).getFileKey());
        }
        iHktsFileRecordService.removeById(hktsFileRecords.get(0).getId());
        return ResultUtil.data("删除成功");
    }

}
